const {User} = require('../../model/user');
const bcrypt = require('bcrypt');

module.exports = async (req, res, next) => {
    const {username, email, role, state, password} = req.body;//修改的信息
    const _id = req.query.id;//要修改的用户id
    //根据id查找数据库
    let user = await User.findOne({_id});

    //密码比对
    const isValid = await bcrypt.compare(password, user.password);
    if (isValid) {//成功
        //更新数据库
        await User.updateOne({_id}, {username, email, role, state});
        //重定向到user页面
        res.redirect('/admin/user');
    } else {
        //错误处理中间件
        next(JSON.stringify({
            path: '/admin/user-edit',
            message: '密码比对失败，不能进行用户信息修改',
            id: _id
        }));
    }
};
